# !/usr/bin/env python3.8
# -*- coding: utf-8 -*-
# @Time : 2021/8/6 15:46
# @Author : minvan
# @Email : jiangming8937@icloud.com
# @File : FeeCalc.py
# @Software: PyCharm

import inspect
import json
import logging
import os
import sys
import time
import datetime
from locust import TaskSet, task, events
from locust.contrib.fasthttp import FastHttpUser
from locust_plugins import jmeter_listener
parent_path = os.path.dirname(sys.path[0])
if parent_path not in sys.path:
    sys.path.append(parent_path)
else:
    pass
from Params.params import params as request_data




#定义日志文件格式
planName =os.path.basename(__file__)+time.strftime("%Y-%m-%d=>%H:%M:%S", time.localtime())+".csv"
reportName = os.path.basename(__file__).split('.py')[0]+datetime.datetime.now().strftime("%Y-%m-%d*%H:%M:%S")+".html"
#定义Locust的配置文件路径
masterConf=os.path.abspath('../Configure/master.conf')

#添加时间监听器
@events.init.add_listener
def on_locust_init(environment, **_kwargs):
    '''

    make report like Jmeter
    :param environment:
    :param _kwargs:
    :return:
    '''
    jmeter_listener.JmeterListener(env=environment,testplan=inspect.stack()[1][3],results_filename=planName)

#定义用户行为，测试脚本在此类下编写
class WebsiteTasks(TaskSet):
    #设置开始执行前的操作 类似tear_up
    def on_start(self):
        self.h=request_data("headers.json")
        self.feeTempServiceList = request_data("FeeTempServiceList.json")


    @task(1)
    def FeetempServiceList(self):
        with self.client.post(path='/spcar/webapi/weapp/feetemp/service/list',json=self.feeTempServiceList,headers=self.h,catch_response=True) as f :
            if f.status_code==200:
                if json.loads(f.content.decode())['msg'] == 'success':
                    f.success()
                else:
                    f.failure(f.text)
            else:
                f.failure(f.text)

    def on_stop(self):
        pass


class WebsiteUser(FastHttpUser):
    tasks = [WebsiteTasks]


if __name__ == '__main__':
    os.system("locust -f %s --html=%s --csv=%s --config=%s"%(os.path.basename(__file__),reportName,reportName,masterConf))

